<?php

namespace backend\components;

use Qcloud\Cos\Client;
use Yii;
use yii\base\Component;
use yii\base\Exception;

/**
 * Class QCloud
 * @package backend\components
 * 腾讯云存储文件封装
 */
class QCloud extends Component
{
    public static $cosClient;

    public function __construct()
    {
        parent::__construct();
        $region = Yii::$app->params['oss']['region'];
        $secretId = Yii::$app->params['oss']['secretId'];
        $secretKey = Yii::$app->params['oss']['secretKey'];
        self::$cosClient = new Client([
            'region' => $region,
            'credentials' => [
                'secretId' => $secretId,
                'secretKey' => $secretKey]]);
    }

    /**
     * @param $path 存储路径(包括文件名字)
     * @param $file 文件
     * @return mixed
     *
     */
    public function upload($path, $file)
    {
        try {
            $result = self::$cosClient->putObject([
                'Bucket' => Yii::$app->params['oss']['bucket'] . '-' . Yii::$app->params['oss']['appId'],
                'Key' => $path,
                'Body' => fopen($file, 'rb'),
            ]);
            return $result;
        } catch (Exception $e) {
            return $e->getMessage();
        }
    }

    /**
     * @param $fileName 文件com后天的全路径 e: bucket1-1250000000.cos.ap-guangzhou.myqcloud.com/doc1/pic1.jpg 中，对象键为 doc1/pic1.jpg
     * @return bool
     */
    public function delete($fileName)
    {
        $result = self::$cosClient->deleteObject(
            [
                'Bucket' => Yii::$app->params['oss']['bucket'] . '-' . Yii::$app->params['oss']['appId'],
                'Key' => $fileName
            ]
        );
        return $result;
    }
}